package com.skytech.component.monitor.enterprise_data_monitoring;


import com.alibaba.fastjson.JSONObject;
import com.skytech.component.monitor.data.MonitorData;
import com.skytech.component.monitor.util.ChromeBrowser;
import com.skytech.component.monitor.util.FormateConnection;
import com.skytech.component.monitor.util.SaveDataUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class HuBeiNewService implements CrawlerScript {
    private static final Logger log = LoggerFactory.getLogger(HuBeiNewService.class);
    @Autowired
    private ChromeBrowser chromeBrowser;

    private static final String province = "湖北";

    @Autowired
    private SaveDataUtil saveDataUtil;


    @Override
    public void start() {
        ChromeDriver driver = chromeBrowser.getChromeDriver();
        String url = "http://59.172.182.106/qyjc/jcjgXxOne.rh";
        boolean b = true;
        int i = 1;
        Elements allElements = null;
        do {
            try {
                Document document = FormateConnection.createConnection(Jsoup.connect(url))
                        .data("pageSize", "100")
                        .data("pageNumber", i + "")
                        .post();
                Elements allElementsNew = document.getAllElements();
                if (allElements != null) {
                    if (allElements.equals(allElementsNew)) {
                        b = false;
                    }
                }
                allElements = allElementsNew;
                List<JSONObject> jsonObjectList = new ArrayList<>();
                Elements elements = allElementsNew.select("#queryForm > table:nth-child(2) > tbody > tr > td > table:nth-child(2) > tbody > tr > td > table:nth-child(3) > tbody > tr:nth-child(2) > td > table > tbody > tr:nth-child(1) > td:nth-child(2) > table:nth-child(2) > tbody > tr:nth-child(1) > td:nth-child(1) > table:nth-child(1) > tbody > tr:nth-child(n+2)");
                for (Element e : elements) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("entName", e.getElementsByTag("td").get(0).text());
                    jsonObject.put("area", e.getElementsByTag("td").get(1).text());
                    jsonObject.put("type", e.getElementsByTag("td").get(2).text());
                    jsonObject.put("industry", e.getElementsByTag("td").get(3).text());
                    jsonObject.put("address", e.getElementsByTag("td").get(4).text());
                    jsonObject.put("href", "http://59.172.182.106/qyjc/" + e.getElementsByTag("a").get(0).attr("href"));
                    jsonObjectList.add(jsonObject);
                }
                detailData(driver, jsonObjectList);
            } catch (Exception e) {
                log.error(e.getMessage());
                b = false;
            }
            i++;
        } while (b);

    }

    private void detailData(ChromeDriver driver, List<JSONObject> jsonObjectList) {

        for (JSONObject jsonObject : jsonObjectList) {
            try {
                driver.switchTo().defaultContent();
                driver.get(jsonObject.getString("href"));
                log.info("当前页面--{}", driver.getCurrentUrl());
            } catch (Exception e) {
                log.error("{}--打开失败", driver.getCurrentUrl());
                continue;
            }
            try {
                driver.findElementByXPath("//*[@id='link_div66']").click();
            } catch (Exception e) {
                log.error("元素点击失败", e.getMessage());
            }
            List<WebElement> webElementList = driver.findElementsByCssSelector("#jcdw_id > option:nth-child(n+2)");

            for (WebElement webElement : webElementList) {
                driver.switchTo().defaultContent();
                try {
                    webElement.click();
                } catch (Exception e) {
                    log.error("元素点击失败", e.getMessage());
                }

                List<WebElement> webElements = driver.findElementsByCssSelector("#jcxm_id > option:nth-child(n+2)");
                for (WebElement e : webElements) {
                    driver.switchTo().defaultContent();
                    try {
                        e.click();
                    } catch (Exception ex) {
                        log.error("元素点击失败", ex.getMessage());
                    }

                    driver.findElementByCssSelector("#jcjg > tbody > tr > td > table > tbody > tr > td > table > tbody > tr:nth-child(3) > td > table > tbody > tr:nth-child(1) > td:nth-child(3) > input[type='image']").click();
                    driver.switchTo().frame("ls");
                    String htmlNew = driver.findElementByTagName("html").getAttribute("outerHTML");
                    Document parse = Jsoup.parse(htmlNew, driver.getCurrentUrl());
                    Elements allElements = parse.getAllElements();
                    Element element = allElements.select("body > table > tbody > tr > td > table > tbody > tr > td > table > tbody > tr > td > table:nth-child(2) > tbody > tr:nth-child(2)").get(0);

                    if (!element.text().contains("暂无数据")) {
                        Elements elements = allElements.select("body > table > tbody > tr > td > table > tbody > tr > td > table > tbody > tr > td > table:nth-child(2) > tbody > tr:nth-child(2n+3)");
                        List<MonitorData> monitorDataList = new ArrayList<>();
                        for (Element elementTmp : elements) {
                            if (!elementTmp.equals(elements.last())) {
                                MonitorData monitorData = new MonitorData();
                                monitorData.setProvince(province);
                                monitorData.setCompanyName(jsonObject.getString("entName"));
                                monitorData.setArea(jsonObject.getString("area"));
                                monitorData.setIndustry(jsonObject.getString("industry"));
                                monitorData.setAddress(jsonObject.getString("address"));
                                monitorData.setPollutionType(jsonObject.getString("type"));
                                monitorData.setId(UUID.randomUUID().toString());
                                monitorData.setMonitorPoint(elementTmp.getElementsByTag("td").get(0).text());
                                monitorData.setMonitorTime(elementTmp.getElementsByTag("td").get(1).text());
                                monitorData.setMonitorInfo(elementTmp.getElementsByTag("td").get(2).text());
                                monitorData.setMonitorValue(elementTmp.getElementsByTag("td").get(3).text());
                                monitorData.setMonitorStandardValue(elementTmp.getElementsByTag("td").get(4).text());
                                monitorData.setCrawlingTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                                monitorDataList.add(monitorData);
                            }
                        }
                        saveDataUtil.saveTag(monitorDataList, province);
                    }
                }
            }

        }
    }


}
